package com.wjs.CarolSecKill.service.imp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjs.CarolSecKill.exception.GlobalException;
import com.wjs.CarolSecKill.mapper.UserMapper;
import com.wjs.CarolSecKill.pojo.User;
import com.wjs.CarolSecKill.service.IUserService;
import com.wjs.CarolSecKill.utils.CookieUtil;
import com.wjs.CarolSecKill.utils.JsonUtil;
import com.wjs.CarolSecKill.utils.Md5Utils;
import com.wjs.CarolSecKill.utils.UUIDUtil;
import com.wjs.CarolSecKill.vo.LoginVo;
import com.wjs.CarolSecKill.vo.RespBean;
import com.wjs.CarolSecKill.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户表
 *
 * @author 作者
 * @date 2022-09-03
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public RespBean doLogin(LoginVo loginVo, HttpServletRequest request, HttpServletResponse response) {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        if(StringUtils.isEmpty(mobile)||StringUtils.isEmpty(password)){
            throw new GlobalException(RespBeanEnum.LOGINVO_ERROR);
        }
        User user = userMapper.selectById(mobile);
        if(user==null){
            throw new GlobalException(RespBeanEnum.LOGINVO_ERROR);
        }
        if(!user.getPassword().equals(Md5Utils.formPassToDBPass(password,user.getSalt()))){
            throw new GlobalException(RespBeanEnum.LOGINVO_ERROR);
        }
        //设置cookie
        String ticket= UUIDUtil.uuid();
        String json = JsonUtil.object2JsonStr(user);
        redisTemplate.opsForValue().set("user:"+ticket,json);
        CookieUtil.setCookie(request,response,"userTicket",ticket);
        return RespBean.success(ticket);
    }

    @Override
    public User getUserByTicket(String ticket, HttpServletRequest request, HttpServletResponse response) {
        if(StringUtils.isEmpty(ticket)){
            return null;
        }
        String json = redisTemplate.opsForValue().get("user:" + ticket);
        User user = JsonUtil.jsonStr2Object(json, User.class);
        if(user!=null){
            CookieUtil.setCookie(request,response,"userTicket",ticket);
        }
        return user;
    }
}
